<script setup>
import { ref } from 'vue';
import { loginAPI } from '@/api/user'
import { useUserStore } from '@/stores/users'

const userStore = useUserStore()
//表达数据
const formData = ref({
	account: '',
	password: ''
})
// 定义表单数据验证规则
const rules = ref({
	account: {
		rules: [
			{ required: true, errorMessage: '请输入登录账号' },
			{ pattern: '^[a-zA-Z0-9]{4,8}$', errorMessage: '登录账号格式不正确' }]
	},
	password: {
		rules: [
			{ required: true, errorMessage: '请输入登录密码' },
			{ pattern: '^\\d{6}$', errorMessage: '登录密码格式不正确' }]
	}
})

// 表单元素的 ref 属性
const form = ref()
//提交表单
const onFormSubmit = async () => {
	// console.log(formData.value);
	try {
		const formData = await form.value.validate()
		const res = await loginAPI(formData)
		// console.log(res);
		if (res.code !== 200) {
			uni.showToast({ title: "登录失败，请重新登录", icon: "none" })
			return
		}
		userStore.token = res.data
		uni.showToast({ title: "登录成功", icon: "none" })
		setTimeout(() => {
			uni.switchTab({
				url: '/pages/my/index'
			});
		}, 1500);
	} catch (error) {
		//验证失败
		console.log(error);
	}
}
</script>

<template>
	<uni-forms :rules="rules" :model="formData" class="login-form" ref="form">
		<uni-forms-item name="account">
			<input type="text" placeholder="请输入账号" v-model="formData.account" class="uni-input-input"
				placeholder-style="color: #818181" />
		</uni-forms-item>
		<uni-forms-item name="password">
			<input type="password" placeholder="请输入密码" v-model="formData.password" class="uni-input-input"
				placeholder-style="color: #818181" />
		</uni-forms-item>
		<button class="submit-button" @click="onFormSubmit">登录</button>
	</uni-forms>
</template>



<style lang="scss" scoped>
@import './styles.scss';
</style>
